import { Column } from "@ant-design/charts"
import InfoCircleOutlined from "@ant-design/icons/InfoCircleOutlined"
import { DailyOrder, OrderQuery, OrderReport, TotalOrders } from "@mallfoundry/report"
import { Card, Col, Divider, Row, Space, Statistic, Typography } from "antd"
import * as dayjs from "dayjs"
import * as _ from "lodash"
import * as React from "react"
import { useEffect, useState } from "react"
import classes from "./monthly-analysis.module.scss"

const { Text } = Typography

const DATE_FIELD_NAME = "时间"

const TOTAL_COUNT_FIELD_NAME = "支付数"

interface MonthlyOrdersColumnProps {
  storeId: string
}

function MonthlyOrdersColumn(props: MonthlyOrdersColumnProps) {
  const { storeId } = props
  const [dailyOrders, setDailyOrders] = useState([] as DailyOrder[])

  const asyncFetch = () => {
    // const dateStart = dayjs().date(1).format("YYYYMMDD")
    // const dateEnd = dayjs().add(1, "month").date(0).format("YYYYMMDD")
    const dateStart = "20200901"
    const dateEnd = "20200930"
    OrderReport
      .queryDailyOrders(
        new OrderQuery()
          .toBuilder()
          .storeId(storeId)
          .dateFrom(dateStart)
          .dateTo(dateEnd)
          .build())
      .then(orders => _.map(orders, order => _.assign(new DailyOrder(), order, {
        [DATE_FIELD_NAME]: dayjs(order.date, "YYYYMMDD").format("YYYY-MM-DD"),
        [TOTAL_COUNT_FIELD_NAME]: order.totalCount,
      })))
      .then(setDailyOrders)
  }
  useEffect(asyncFetch, [storeId])
  const config = {
    height: 60,
    autoFit: true,
    smooth: true,
    padding: [12, 0, 12, 0],
    data: dailyOrders,
    xField: DATE_FIELD_NAME,
    yField: TOTAL_COUNT_FIELD_NAME,
    xAxis: {
      line: null,
      label: null,
    },
    yAxis: {
      label: null,
      grid: null,
    },
    tooltip: {
      fields: [DATE_FIELD_NAME, TOTAL_COUNT_FIELD_NAME],
      showTitle: false,
    },
  }
  return <Column {...config} />
}


interface MonthlyOrdersProps {
  storeId: string
}

export default function MonthlyOrders(props: MonthlyOrdersProps) {
  const { storeId } = props
  const [dailyTotalOrders, setDailyTotalOrders] = useState(new TotalOrders())

  useEffect(() => {
    OrderReport.queryTotalOrders(
      new OrderQuery()
        .toBuilder().storeId(storeId)
        .build())
      .then(setDailyTotalOrders)
  }, [storeId])

  return (
    <Card size="small">
      <Row justify="space-between">
        <Col>
          <Statistic title="支付笔数" className={classes.MonthlyTotalStatistic} value={dailyTotalOrders.totalCount}/>
        </Col>
        <Col>
          <Text type="secondary">
            <InfoCircleOutlined/>
          </Text>
        </Col>
      </Row>
      <MonthlyOrdersColumn storeId={storeId}/>
      <Divider/>
      <Space>
        <Text>转化率</Text>
        <Text>60%</Text>
      </Space>
    </Card>
  )
}
